package com.common.frame.utils;

import android.content.Context;
import android.os.IBinder;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

/**
 * 输入法工具类
 */
public class InputMethodUtils {

    /**
     * 将EditText的光标移动到最后面
     */
    public static void cursorToLast(EditText editText){
        //将光标移至文字末尾
        editText.setSelection(editText.getText().length());
    }

    /**
     * EditText 获取焦点并且弹出输入法
     */
    public static void setEditTextFocus(EditText editText){
        editText.postDelayed(() -> {
            editText.setFocusable(true);
            editText.setFocusableInTouchMode(true);
            editText.requestFocus();
            InputMethodManager imm = (InputMethodManager) editText.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.showSoftInput(editText, InputMethodManager.RESULT_UNCHANGED_SHOWN);
        }, 100);
    }

    /**
     * EditText 获取焦点并且弹出输入法
     */
    public static void setEditTextFocusOnly(EditText editText){
        editText.setFocusable(true);
        editText.setFocusableInTouchMode(true);
        editText.requestFocus();
        hideSoftInput(editText);
    }

    /**
     * 强制关闭软键盘
     * @param editText
     */
    public static void hideSoftInput(EditText editText){
        if(editText != null){
            InputMethodManager inputMethodManager = (InputMethodManager) AppGlobals.getApplication().getSystemService(Context.INPUT_METHOD_SERVICE);
            inputMethodManager.hideSoftInputFromWindow(editText.getWindowToken(), 0);
        }
    }

    /**
     * 强制关闭软键盘
     * @param editText
     */
    public static void hideSoftInput(IBinder editText){
        if(editText != null){
            InputMethodManager inputMethodManager = (InputMethodManager) AppGlobals.getApplication().getSystemService(Context.INPUT_METHOD_SERVICE);
            inputMethodManager.hideSoftInputFromWindow(editText, 0);
        }
    }


}
